//
//  RBTabBarController.m
//  Base
//
//  Created by 蓝其 on 16/10/18.
//  Copyright © 2016年 蓝其. All rights reserved.
//

#import "RBTabBarController.h"
#import "UIView+YYAdd.h"
#import "NSObject+YYAddForKVO.h"
#import "NSObject+YYAdd.h"
#import "RBDefine.h"
#import <Masonry.h>

@interface RBTabBarController ()

@property(nonatomic, strong)NSArray *buttons;
@property(nonatomic, strong)NSArray *indexes;
@property(nonatomic, strong)NSArray *proportions;

@property(nonatomic, strong) UIView *line;

@end

@implementation RBTabBarController

#pragma mark - LifeCycle

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])
    {
        self.autoSelectVC = YES;
        kRBWeakSelf;
        [self.tabBar addObserverBlockForKeyPath:@"frame" block:^(id  _Nonnull obj, id  _Nonnull oldVal, id  _Nonnull newVal) {
            [weak_self adjustTabBarFrame];
        }];
    }
    return self;
}

- (void)dealloc
{
    [self.tabBar removeObserverBlocks];
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    [self clearUITabBarButtons];
    [self layOutSubviewsOnTabBar];
}

#pragma mark - Event

- (void)buttonTapped: (UIButton *)button
{
    NSInteger index = [self.buttons indexOfObject:button];
    if (self.tabBarButtonTappedBlock)
    {
        self.tabBarButtonTappedBlock(self, button, index, self.selectedTabBarButtonIndex);
    }
    if(index != self.selectedTabBarButtonIndex && self.autoSelectVC)
    {
        self.selectedTabBarButtonIndex = index;
    }
}

#pragma mark - Public

- (void)setTabBarButtons:(NSArray<__kindof UIButton *> *)buttons withIndexesOfViewController:(NSArray<__kindof NSNumber *> *)indexes proportionsOfTabBarWidth:(NSArray<__kindof NSNumber *> *)proportions
{
    self.buttons = buttons;
    self.indexes = indexes;
    self.proportions = proportions;
    [self clearUIButtons];
    [self layOutSubviewsOnTabBar];
    self.selectedTabBarButtonIndex = 0;
}

- (UIButton *)tabBarButtonAtIndex:(NSInteger)index
{
    return index < self.buttons.count? self.buttons[index]: nil;
}

- (CGRect)frameForTabBarButtonAtIndex:(NSInteger)index
{
    return [[self tabBarButtonAtIndex:index] frame];
}

- (void)layOutSubviewsOnTabBar
{
    CGFloat height = MIN(self.tabBar.frame.size.height, 49.0);
    CGFloat width = 0;
    CGFloat y = 0;
    CGFloat x = 0;
    UIButton *button;
    for (NSInteger index = 0; index < self.buttons.count; index++)
    {
        button = self.buttons[index];
        width = self.tabBar.frame.size.width * [self.proportions[index] floatValue];
        [button setFrame:CGRectMake(x, y, width, height)];
        [button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchDown];
//        button.adjustsImageWhenHighlighted = NO;
        [self.tabBar addSubview:button];
        x += width;
    }
    
    //加一条线,没做处理
//    if (!_line)
//    {
//        self.line = [UIView new];
//        self.line.backgroundColor = [UIColor lightGrayColor];
//        [self.tabBar addSubview:self.line];
//    }
    self.line.frame = CGRectMake(0, 0, self.tabBar.frame.size.width, 0.5);
    [self.tabBar bringSubviewToFront:self.line];
}

- (void)setSelectedTabBarButtonIndex:(NSInteger)index
{
    if (index >= self.buttons.count)
    {
        return;
    }
    NSInteger indexOfViewController = [self.indexes[index] integerValue];
    if (indexOfViewController != NSNotFound)
    {
        UIButton *lastButton = [self tabBarButtonAtIndex:_selectedTabBarButtonIndex];
        UIButton *currentButton = [self tabBarButtonAtIndex:index];
        //切换按钮
        lastButton.selected = NO;
        currentButton.selected = YES;
        //切换控制器
        self.selectedIndex = indexOfViewController;
        //更新选中序号
        _selectedTabBarButtonIndex = index;
    }
}

#pragma mark - Private

//强制调整一下,不然可能会跳动
- (void)adjustTabBarFrame
{
    if (self.tabBar.height < kRBiPhoneXTabbarHeight - 1 || self.tabBar.height + self.tabBar.top < self.view.height)
    {
        self.tabBar.frame = ({
            CGRect frame = self.tabBar.frame;
            frame.size.height = kRBiPhoneXTabbarHeight;
            frame.origin.y = self.view.height - frame.size.height;
            frame;
        });
    }
}

- (void)clearUIButtons
{
    for (UIView *subview in self.tabBar.subviews)
    {
        if ([subview isKindOfClass:[UIButton class]])
        {
            [subview removeFromSuperview];
        }
    }
}

#pragma mark -
- (void)clearUITabBarButtons
{
    for (UIView *subview in self.tabBar.subviews)
    {
        if ([subview isKindOfClass:NSClassFromString(@"UITabBarButton")])
        {
            subview.hidden = YES;
            subview.frame = CGRectZero;
            subview.alpha = 0;
            subview.userInteractionEnabled = NO;
            subview.clipsToBounds = YES;
        }
    }
}

@end
